package com.smartum.mpr.json.parsers;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public abstract class EntityParser<T> {

	private ObjectMapper mapper = new ObjectMapper();
	{
		mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
	}

	public T parseEntity(String json) throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(json, getEntityClass());
	}

	public List<T> parseEntityList(String json) throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, getEntityClass()));
	}

	public String writeEntity(T entity) throws JsonGenerationException, JsonMappingException, IOException {
		Writer writer = new StringWriter();
		mapper.writeValue(writer, entity);
		return writer.toString();
	}

	public String writeEntityList(List<T> entity) throws JsonGenerationException, JsonMappingException, IOException {
		Writer writer = new StringWriter();
		mapper.writeValue(writer, entity);
		return writer.toString();
	}
	
	public JsonNode writeInNode(T entity) throws JsonGenerationException, JsonMappingException, IOException {
		String content = writeEntity(entity);
		return mapper.readTree(content);
	}
	
	public JsonNode writeInNode(List<T> entity) throws JsonGenerationException, JsonMappingException, IOException {
		String content = writeEntityList(entity);
		return mapper.readTree(content);
	}
	

	public ObjectMapper getMapper() {
		return mapper;
	}

	public abstract Class<T> getEntityClass();
}
